package com.example.auth.service.impl;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.example.auth.enums.BusinessErrorCode;
import com.example.auth.model.VO.UserLoginVO;
import com.example.auth.model.base.Result;
import com.example.auth.model.domain.SysUser;
import com.example.auth.model.req.LoginReq;
import com.example.auth.model.req.RegisterReq;
import com.example.auth.service.ILoginService;
import com.example.auth.service.ISysUserService;
import com.example.auth.utils.ClassUtil;
import com.example.auth.utils.JsonUtil;
import com.example.auth.utils.MD5Utils;
import com.example.auth.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author xijie.wang
 * @decription:登录注册
 * @date 2022-04-11 17:43
 */
@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {


	@Autowired
	private ISysUserService userService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<UserLoginVO> login(LoginReq req) {

		String phone = req.getPhone();
		SysUser user = userService.getUserByPhone(phone);
		String password = user.getPassword();
		if (user == null || StringUtils.isBlank(password)) {
			return Result.fail(BusinessErrorCode.USER_PHONE_ERROR);
		}

		//密码校验
		String salt = user.getSalt();
		if (!password.equals(MD5Utils.string2MD5(req.getPassword() + salt))) {
			return Result.fail(BusinessErrorCode.USER_PHONE_ERROR);
		}

		UserLoginVO userLoginVO = ClassUtil.copyProperties(UserLoginVO.class, user);
		//生成token
		SaLoginModel model = SaLoginConfig.setExtraData(JsonUtil.objectToMap(user));
		StpUtil.login(user.getId(), model);
		String tokenValue = StpUtil.getTokenValue();

		//封装成功登录的token及用户信息
		userLoginVO.setToken(tokenValue);
		StpUtil.getSession().set("user", user);
		//更新最后登录时间
		userService.updateLastLoginTimeById(user.getId(), new Date());

		return Result.ok(userLoginVO);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<String> register(RegisterReq req) {

		String confirmPwd = req.getConfirmPwd();
		String password = req.getPassword();

		if (!password.equals(confirmPwd)) {
			return Result.fail(BusinessErrorCode.TWO_TIME_PWD_ERROR);
		}
		String phone = req.getPhone();
		SysUser user = userService.getUserByPhone(phone);
		if (user != null) {
			return Result.fail(BusinessErrorCode.PHONE_EXIST_ERROR);
		}
		//设置登录密码
		String salt = StrUtils.getComplexRandomString(16);
		String enPassword = MD5Utils.string2MD5(password + salt);
		SysUser userSave = SysUser.builder()
				.name(req.getName())
				.password(enPassword)
				.phone(phone)
				.salt(salt)
				.build();
		userService.save(userSave);

		return Result.ok(userSave.getPhone());
	}

}
